<?php
/**
 * 男友类
 */
class Friend {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * 发送男友请求
     * 
     * @param int $userId 发送请求的用户ID
     * @param int $friendId 接收请求的用户ID
     * @return array 包含状态和消息的数组
     */
    public function sendFriendRequest($userId, $friendId) {
        // 检查是否已经是男友
        $existingFriendship = $this->db->fetch(
            "SELECT * FROM friendships WHERE 
            (user_id = ? AND friend_id = ?) OR 
            (user_id = ? AND friend_id = ?)",
            [$userId, $friendId, $friendId, $userId]
        );
        
        if ($existingFriendship) {
            if ($existingFriendship['status'] == 'accepted') {
                return ['status' => false, 'message' => '你们已经是男友了'];
            } elseif ($existingFriendship['status'] == 'pending') {
                if ($existingFriendship['user_id'] == $userId) {
                    return ['status' => false, 'message' => '你已经发送过男友请求，等待对方接受'];
                } else {
                    return ['status' => false, 'message' => '对方已经向你发送了男友请求，请先处理'];
                }
            } elseif ($existingFriendship['status'] == 'rejected') {
                // 如果之前被拒绝，可以重新发送请求
                try {
                    $this->db->query(
                        "UPDATE friendships SET status = 'pending', created_at = NOW() WHERE id = ?",
                        [$existingFriendship['id']]
                    );
                    
                    // 添加通知
                    $this->addFriendRequestNotification($userId, $friendId);
                    
                    return ['status' => true, 'message' => '男友请求已发送'];
                } catch (Exception $e) {
                    return ['status' => false, 'message' => '发送请求失败，请稍后再试'];
                }
            }
        }
        
        // 发送新的男友请求
        try {
            $this->db->query(
                "INSERT INTO friendships (user_id, friend_id, status) VALUES (?, ?, 'pending')",
                [$userId, $friendId]
            );
            
            // 添加通知
            $this->addFriendRequestNotification($userId, $friendId);
            
            return ['status' => true, 'message' => '男友请求已发送'];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '发送请求失败，请稍后再试'];
        }
    }
    
    /**
     * 接受男友请求
     * 
     * @param int $friendshipId 男友关系ID
     * @param int $userId 当前用户ID
     * @return array 包含状态和消息的数组
     */
    public function acceptFriendRequest($friendshipId, $userId) {
        // 检查请求是否存在且状态为pending
        $friendship = $this->db->fetch(
            "SELECT * FROM friendships WHERE id = ? AND friend_id = ? AND status = 'pending'",
            [$friendshipId, $userId]
        );
        
        if (!$friendship) {
            return ['status' => false, 'message' => '男友请求不存在或已处理'];
        }
        
        try {
            // 更新状态为accepted
            $this->db->query(
                "UPDATE friendships SET status = 'accepted', updated_at = NOW() WHERE id = ?",
                [$friendshipId]
            );
            
            // 添加通知
            $this->addFriendAcceptedNotification($friendship['user_id'], $userId);
            
            return ['status' => true, 'message' => '已接受男友请求'];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '处理请求失败，请稍后再试'];
        }
    }
    
    /**
     * 拒绝男友请求
     * 
     * @param int $friendshipId 男友关系ID
     * @param int $userId 当前用户ID
     * @return array 包含状态和消息的数组
     */
    public function rejectFriendRequest($friendshipId, $userId) {
        // 检查请求是否存在且状态为pending
        $friendship = $this->db->fetch(
            "SELECT * FROM friendships WHERE id = ? AND friend_id = ? AND status = 'pending'",
            [$friendshipId, $userId]
        );
        
        if (!$friendship) {
            return ['status' => false, 'message' => '男友请求不存在或已处理'];
        }
        
        try {
            // 更新状态为rejected
            $this->db->query(
                "UPDATE friendships SET status = 'rejected', updated_at = NOW() WHERE id = ?",
                [$friendshipId]
            );
            
            return ['status' => true, 'message' => '已拒绝男友请求'];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '处理请求失败，请稍后再试'];
        }
    }
    
    /**
     * 删除男友
     * 
     * @param int $userId 当前用户ID
     * @param int $friendId 要删除的男友ID
     * @return array 包含状态和消息的数组
     */
    public function deleteFriend($userId, $friendId) {
        try {
            $this->db->query(
                "DELETE FROM friendships WHERE 
                (user_id = ? AND friend_id = ?) OR 
                (user_id = ? AND friend_id = ?)",
                [$userId, $friendId, $friendId, $userId]
            );
            
            return ['status' => true, 'message' => '已删除男友'];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '删除男友失败，请稍后再试'];
        }
    }
    
    /**
     * 获取男友列表
     * 
     * @param int $userId 用户ID
     * @return array 男友列表
     */
    public function getFriends($userId) {
        return $this->db->fetchAll(
            "SELECT u.id, u.username, u.nickname, u.avatar, f.intimacy, f.id as friendship_id
             FROM friendships f
             JOIN users u ON (f.user_id = u.id AND f.friend_id = ?) OR (f.friend_id = u.id AND f.user_id = ?)
             WHERE f.status = 'accepted'
             ORDER BY f.intimacy DESC",
            [$userId, $userId]
        );
    }
    
    /**
     * 获取男友请求列表
     * 
     * @param int $userId 用户ID
     * @return array 男友请求列表
     */
    public function getFriendRequests($userId) {
        return $this->db->fetchAll(
            "SELECT f.id, u.id as user_id, u.username, u.nickname, u.avatar, f.created_at
             FROM friendships f
             JOIN users u ON f.user_id = u.id
             WHERE f.friend_id = ? AND f.status = 'pending'
             ORDER BY f.created_at DESC",
            [$userId]
        );
    }
    
    /**
     * 获取已发送的男友请求
     * 
     * @param int $userId 用户ID
     * @return array 已发送的男友请求列表
     */
    public function getSentFriendRequests($userId) {
        return $this->db->fetchAll(
            "SELECT f.id, u.id as user_id, u.username, u.nickname, u.avatar, f.created_at
             FROM friendships f
             JOIN users u ON f.friend_id = u.id
             WHERE f.user_id = ? AND f.status = 'pending'
             ORDER BY f.created_at DESC",
            [$userId]
        );
    }
    
    /**
     * 检查是否是男友
     * 
     * @param int $userId 用户ID
     * @param int $friendId 男友ID
     * @return bool 是否是男友
     */
    public function isFriend($userId, $friendId) {
        $friendship = $this->db->fetch(
            "SELECT * FROM friendships 
             WHERE ((user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?))
             AND status = 'accepted'",
            [$userId, $friendId, $friendId, $userId]
        );
        
        return $friendship ? true : false;
    }
    
    /**
     * 获取男友关系状态
     * 
     * @param int $userId 用户ID
     * @param int $friendId 男友ID
     * @return string|false 男友关系状态或false
     */
    public function getFriendshipStatus($userId, $friendId) {
        $friendship = $this->db->fetch(
            "SELECT * FROM friendships 
             WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)",
            [$userId, $friendId, $friendId, $userId]
        );
        
        return $friendship ? $friendship['status'] : false;
    }
    
    /**
     * 获取男友关系ID
     * 
     * @param int $userId 用户ID
     * @param int $friendId 男友ID
     * @return int|false 男友关系ID或false
     */
    public function getFriendshipId($userId, $friendId) {
        $friendship = $this->db->fetch(
            "SELECT id FROM friendships 
             WHERE ((user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?))
             AND status = 'accepted'",
            [$userId, $friendId, $friendId, $userId]
        );
        
        return $friendship ? $friendship['id'] : false;
    }
    
    /**
     * 获取男友列表（getFriends的别名）
     * 
     * @param int $userId 用户ID
     * @return array 男友列表
     */
    public function getFriendList($userId) {
        return $this->getFriends($userId);
    }
    
    /**
     * 增加亲密度
     * 
     * @param int $friendshipId 男友关系ID
     * @param int $points 增加的点数
     * @param int $taskId 相关任务ID
     * @param string $description 描述
     * @return array 包含状态和消息的数组
     */
    public function increaseIntimacy($friendshipId, $points, $taskId = null, $description = '') {
        try {
            // 更新亲密度
            $this->db->query(
                "UPDATE friendships SET intimacy = intimacy + ? WHERE id = ?",
                [$points, $friendshipId]
            );
            
            // 记录亲密度日志
            $this->db->query(
                "INSERT INTO intimacy_logs (friendship_id, task_id, points, description) VALUES (?, ?, ?, ?)",
                [$friendshipId, $taskId, $points, $description]
            );
            
            // 获取男友关系信息
            $friendship = $this->db->fetch("SELECT * FROM friendships WHERE id = ?", [$friendshipId]);
            
            // 添加通知
            $this->addIntimacyIncreaseNotification($friendship['user_id'], $friendship['friend_id'], $points);
            $this->addIntimacyIncreaseNotification($friendship['friend_id'], $friendship['user_id'], $points);
            
            return [
                'status' => true, 
                'message' => '亲密度增加成功',
                'points' => $points,
                'new_intimacy' => $friendship['intimacy']
            ];
        } catch (Exception $e) {
            return ['status' => false, 'message' => '增加亲密度失败，请稍后再试'];
        }
    }
    
    /**
     * 获取亲密度历史记录
     * 
     * @param int $friendshipId 男友关系ID
     * @return array 亲密度历史记录
     */
    public function getIntimacyLogs($friendshipId) {
        return $this->db->fetchAll(
            "SELECT il.*, t.title as task_title
             FROM intimacy_logs il
             LEFT JOIN tasks t ON il.task_id = t.id
             WHERE il.friendship_id = ?
             ORDER BY il.created_at DESC",
            [$friendshipId]
        );
    }
    
    /**
     * 添加男友请求通知
     * 
     * @param int $senderId 发送者ID
     * @param int $receiverId 接收者ID
     */
    private function addFriendRequestNotification($senderId, $receiverId) {
        $sender = $this->db->fetch("SELECT username, nickname FROM users WHERE id = ?", [$senderId]);
        $senderName = $sender['nickname'] ?? $sender['username'];
        
        $content = $senderName . ' 向您发送了男友请求';
        
        $this->db->query(
            "INSERT INTO notifications (user_id, type, related_id, content) VALUES (?, 'friend_request', ?, ?)",
            [$receiverId, $senderId, $content]
        );
    }
    
    /**
     * 添加男友接受通知
     * 
     * @param int $senderId 发送者ID
     * @param int $receiverId 接收者ID
     */
    private function addFriendAcceptedNotification($senderId, $receiverId) {
        $receiver = $this->db->fetch("SELECT username, nickname FROM users WHERE id = ?", [$receiverId]);
        $receiverName = $receiver['nickname'] ?? $receiver['username'];
        
        $content = $receiverName . ' 接受了您的男友请求';
        
        $this->db->query(
            "INSERT INTO notifications (user_id, type, related_id, content) VALUES (?, 'friend_accepted', ?, ?)",
            [$senderId, $receiverId, $content]
        );
    }
    
    /**
     * 添加亲密度增加通知
     * 
     * @param int $userId 用户ID
     * @param int $friendId 男友ID
     * @param int $points 增加的点数
     */
    private function addIntimacyIncreaseNotification($userId, $friendId, $points) {
        $friend = $this->db->fetch("SELECT username, nickname FROM users WHERE id = ?", [$friendId]);
        $friendName = $friend['nickname'] ?? $friend['username'];
        
        $content = '您与 ' . $friendName . ' 的亲密度增加了 ' . $points . ' 点';
        
        $this->db->query(
            "INSERT INTO notifications (user_id, type, related_id, content) VALUES (?, 'intimacy_increase', ?, ?)",
            [$userId, $friendId, $content]
        );
    }
}
